import 'package:flutter/material.dart';
import 'package:flutter_trip/DAO/TripDAO.dart';
import 'package:flutter_trip/Model/CommonItemModel.dart';
import 'package:flutter_trip/Model/SearchModel.dart';
import 'package:flutter_trip/Widget/SearchBarWidget.dart';

class SearchPage extends StatefulWidget {
  /// 是否显示返回按钮
  final bool isShowBackButton;
  final String defaultKeyword;
  SearchPage({this.isShowBackButton = false,this.defaultKeyword});

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage>
    with AutomaticKeepAliveClientMixin {
  /// 搜索模型
  SearchModel _searchModel;

  String _keyword;

  /// 搜索图标类型
  final List<String> _searchItemIconTypes = [
    'channelgroup',
    'gs',
    'plane',
    'train',
    'cruise',
    'district',
    'food',
    'hotel',
    'huodong',
    'shop',
    'sight',
    'ticket',
    'travelgroup'
  ];

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        body: Column(children: <Widget>[_appBar(context), _listView(context)]));
  }

  Widget _appBar(BuildContext context) {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        child: SearchBarWidget(
          isHomeSearchBar: false,
          onChanged: _onChanged,
          defaultKeyword: widget.defaultKeyword,
          isShowBackButton: widget.isShowBackButton,
          backButtonClick: () => Navigator.of(context).pop(),
          microphoneButtonClick: () =>
              Navigator.of(context).pushNamed('/speakSearch'),
        ));
  }

  Widget _listView(BuildContext context) {
    return Expanded(
        child: MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: ListView.builder(
                itemCount: _searchModel?.data?.length ?? 0,
                itemBuilder: (context, index) {
                  if (_searchModel == null ||
                      (_searchModel?.data?.length ?? 0) == 0) return null;
                  return _searchResultItem(_searchModel.data[index]);
                })));
  }

  void _onChanged(String text) async {
    _keyword = text;
    if (text.length > 0) {
      SearchModel searchModel = await TripDAO.loadSearchData(keyword: _keyword);
      if (searchModel != null && searchModel?.keyword == _keyword) {
        setState(() {
          // 只有当前关键词和服务端一致时 才更新
          _searchModel = searchModel;
        });
      }
    } else {
      // 没有内容 清空
      setState(() {
        _searchModel = null;
      });
    }
  }

  Widget _searchResultItem(SearchItemModel itemModel) {
    if (itemModel == null) return null;
    double maxWidth = MediaQuery.of(context).size.width - 30 - 15;
    return GestureDetector(
        onTap: () => Navigator.of(context).pushNamed('/webView',
            arguments: CommonItemModel(url: itemModel.url, title: '详情')),
        child: Container(
            decoration: BoxDecoration(
                color: Colors.white,
                border:
                    Border(bottom: BorderSide(color: Colors.grey, width: 0.5))),
            child: Row(children: <Widget>[
              _searchResultItemIcon(itemModel.type),
              Column(children: <Widget>[
                _searchResultItemTitle(
                    itemModel: itemModel, maxWidth: maxWidth),
                _searchResultItemSubTitle(
                    itemModel: itemModel, maxWidth: maxWidth)
              ])
            ])));
  }

  Widget _searchResultItemIcon(String type) {
    String name = 'hotel';
    for (String item in _searchItemIconTypes) {
      if (item == type) {
        name = type;
        break;
      }
    }

    return Image.asset('images/type_$name.png', width: 30.0, height: 30.0);
  }

  Widget _searchResultItemTitle({SearchItemModel itemModel, double maxWidth}) {
    return Container(
        width: maxWidth,
        child: RichText(
            text: TextSpan(
                children: _searchResultItemTitleSpans(itemModel: itemModel))));
  }

  Widget _searchResultItemSubTitle(
      {SearchItemModel itemModel, double maxWidth}) {
    return Container(
        margin: EdgeInsets.only(top: 5.0, bottom: 2),
        width: maxWidth,
        child: RichText(
            text: TextSpan(
                children:
                    _searchResultItemSubTitleSpans(itemModel: itemModel))));
  }

  List<TextSpan> _searchResultItemTitleSpans({SearchItemModel itemModel}) {
    List<TextSpan> list = List<TextSpan>();
    List arr = (itemModel.word ?? '').split(_keyword);
    TextStyle normalStyle = TextStyle(fontSize: 16, color: Colors.black);
    TextStyle highlightedStyle = TextStyle(fontSize: 16, color: Colors.orange);
    if (arr.length == 1) {
      list.add(TextSpan(text: itemModel.word, style: normalStyle));
    } else {
      for (String str in arr) {
        if (str.isNotEmpty) {
          list.add(TextSpan(text: _keyword, style: highlightedStyle));
          list.add(TextSpan(text: str, style: normalStyle));
        }
      }
    }

    TextStyle greyStyle = TextStyle(fontSize: 16, color: Colors.grey);
    list.add(
        TextSpan(text: ' ' + (itemModel.districtname ?? ''), style: greyStyle));
    list.add(
        TextSpan(text: ' ' + (itemModel.zonename ?? ''), style: greyStyle));
    return list;
  }

  List<TextSpan> _searchResultItemSubTitleSpans({SearchItemModel itemModel}) {
    List<TextSpan> list = List<TextSpan>();
    TextStyle highlightedStyle = TextStyle(fontSize: 16, color: Colors.orange);
    list.add(TextSpan(text: (itemModel.price ?? ''), style: highlightedStyle));
    list.add(TextSpan(
        text: ' ' + (itemModel.star ?? ''),
        style: TextStyle(color: Colors.grey, fontSize: 14)));
    return list;
  }
}
